package com.xuzimian.demo.java.proxy.dynamic

import com.xuzimian.demo.java.proxy.SubjectNoInterfaces
import net.sf.cglib.proxy.Enhancer
import net.sf.cglib.proxy.MethodInterceptor
import net.sf.cglib.proxy.MethodProxy
import java.lang.reflect.Method


fun main() {
    val enhancer = Enhancer()
    // 设置要代理的目标类
    enhancer.setSuperclass(SubjectNoInterfaces::class.java)
    // 设置要代理的拦截器
    enhancer.setCallback(CglibHandler(SubjectNoInterfaces()))

    // 生成代理类的实例
    val subject = enhancer.create() as SubjectNoInterfaces
    subject.processBusiness()
}

class CglibHandler(private val target: Any) : MethodInterceptor {

    @Throws(Throwable::class)
    override fun intercept(proxy: Any, method: Method, args: Array<Any>,
                           methodProxy: MethodProxy): Any {
        doBefore()
        val result = methodProxy.invoke(target, args)
        doAfter()
        return result
    }

    fun doBefore() {
        println("Before ...")
    }

    fun doAfter() {
        println("After ...")
    }
}